<template>
  <div class="login">
    <h3>后台管理系统</h3>
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item prop="adminname">
        <el-input v-model="form.adminname">
          <template #prefix>
            <el-icon :size="20">
              <User />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="form.password" type="password" show-password>
          <template v-slot:prefix>
            <el-icon>
              <Lock />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios';
import { User, Lock } from '@element-plus/icons-vue';
import { Login } from '../service/admin';
export default {
  components: {
    User,
    Lock
  },
  data() {
    return {
      form: {
        //登录的用户名adminname,密码password和后台接口一致
        adminname: '',
        password: ''
      },
      rules: {
        adminname: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    };
  },
  methods: {
    onSubmit() {
      let formEl = this.$refs.form; //找到表单元素
      if (!formEl) return;
      formEl.validate(valid => {
        //validate表单校验方法
        //表单校验通过 valid是true 否则 valid是false
        if (valid) {
          // console.log('submit!',this.form)
          Login(this.form).then(res => {
            // console.log(res);
            if (res.code === '200') {
              //把登录后的用户信息存储到仓库里
              this.$store.commit('setUserInfo', res.data);
              this.$router.push('/home');
            }
          });
        } else {
          console.log('error submit!');
          return false;
        }
      });
    }
  }
};
</script>
<style scoped>
.login {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
  padding: 8px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate3d(-50%, -50%, 0);
}

.login h3 {
  text-align: center;
}

.login button {
  margin: 0 auto;
}
</style>